package com.carkeeper.service.impl;

import com.carkeeper.mapper.FileMapper;
import com.carkeeper.pojo.FilePO;
import com.carkeeper.service.FileService;
import com.carkeeper.utils.FastDFSClient;
import com.carkeeper.utils.FastDFSFile;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author: geekyangyang
 * @Date: 2020/6/5 10:32
 * @Description
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileMapper fileMapper;

    @Override
    public String upload(MultipartFile file) throws IOException {


        //1. 获取完整的文件名
        String originalFilename = file.getOriginalFilename();
        //2. 获取文件扩展名
        if (StringUtils.isEmpty(originalFilename)) {
            return "上传失败";
        }
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //3. 获取文件内容
        byte[] content = file.getBytes();
        //4. 将以上内封装成文件上传对象
        FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, content, extName);
        //5. 上传
        String[] path = FastDFSClient.upload(fastDFSFile);
        //6. 拼接完整的文件访问路径
        String url = FastDFSClient.getTrackerUrl() + path[0] + "/" + path[1];
//        url=url.replace("http://68.79.1.140:8080","http://68.79.1.140:8241");
        FilePO filePO = new FilePO();
        filePO.setFileName(originalFilename);
        filePO.setFilePath(url);

        fileMapper.insert(filePO);
        //7. 返回
        return url;

    }
}
